'use client';

import { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';

interface Order {
  orderId: string;
  openId: string;
  goodsId: number;
  orderTime: string;
  orderState: number;
  userName: string;
  goodsName: string;
  goodsPrice: number;
  goodsImage: string;
  goodsAddress: string;
  tel: string;
  customerName: string;
  trading: number;
}

interface OrderDialogProps {
  order: Order | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSave: (order: Order) => void;
}

export function OrderDialog({ order, open, onOpenChange, onSave }: OrderDialogProps) {
  const [editedOrder, setEditedOrder] = useState<Order | null>(null);

  useEffect(() => {
    if (order) {
      setEditedOrder(order);
    }
  }, [order]);

  if (!order || !editedOrder) return null;

  const handleSave = async () => {
    try {
      const response = await fetch(`/api/orders/${order.orderId}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(editedOrder),
      });

      if (!response.ok) {
        throw new Error('更新订单信息失败');
      }

      onSave(editedOrder);
      onOpenChange(false);
    } catch (error) {
      console.error('更新订单信息失败:', error);
    }
  };

  const getOrderStatusText = (status: number) => {
    switch (status) {
      case 0:
        return '待付款';
      case 1:
        return '待发货';
      case 2:
        return '待收货';
      case 3:
        return '已完成';
      case 4:
        return '已取消';
      default:
        return '未知状态';
    }
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>订单详情</DialogTitle>
        </DialogHeader>
        <div className="grid gap-4 py-4">
          <div className="grid grid-cols-4 items-center gap-4">
            <label className="text-right">订单ID</label>
            <div className="col-span-3">
              <span className="text-gray-700">{editedOrder.orderId}</span>
            </div>
          </div>
          <div className="grid grid-cols-4 items-center gap-4">
            <label className="text-right">商品信息</label>
            <div className="col-span-3 flex items-center space-x-2">
              <img
                src={editedOrder.goodsImage}
                alt={editedOrder.goodsName}
                className="h-12 w-12 rounded object-cover"
              />
              <div>
                <div className="font-medium">{editedOrder.goodsName}</div>
                <div className="text-sm text-gray-500">¥{editedOrder.goodsPrice.toFixed(2)}</div>
              </div>
            </div>
          </div>
          <div className="grid grid-cols-4 items-center gap-4">
            <label className="text-right">买家信息</label>
            <div className="col-span-3">
              <div>{editedOrder.userName}</div>
              <div className="text-sm text-gray-500">{editedOrder.tel}</div>
            </div>
          </div>
          <div className="grid grid-cols-4 items-center gap-4">
            <label className="text-right">收货地址</label>
            <div className="col-span-3">
              <span className="text-gray-700">{editedOrder.goodsAddress}</span>
            </div>
          </div>
          <div className="grid grid-cols-4 items-center gap-4">
            <label className="text-right">下单时间</label>
            <div className="col-span-3">
              <span className="text-gray-700">{formatDate(editedOrder.orderTime)}</span>
            </div>
          </div>
          <div className="grid grid-cols-4 items-center gap-4">
            <label className="text-right">订单状态</label>
            <div className="col-span-3">
              <Select
                value={editedOrder.orderState.toString()}
                onValueChange={(value) => setEditedOrder({ ...editedOrder, orderState: parseInt(value) })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="选择订单状态" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="0">待付款</SelectItem>
                  <SelectItem value="1">待发货</SelectItem>
                  <SelectItem value="2">待收货</SelectItem>
                  <SelectItem value="3">已完成</SelectItem>
                  <SelectItem value="4">已取消</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>取消</Button>
          <Button onClick={handleSave}>保存</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}